package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Role;
import com.atguigu.result.Result;
import com.atguigu.result.ResultCodeEnum;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RoleService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @PACKAGE_NAME: com.atguigu.controller
 * @CLASSNAME: RoleController
 * @AUTHOR: zhangsan
 * @DATE: 2024/4/14 18:29
 * @SINCE 17.0.7
 * @DESCRIPTION: RoleController 角色控制层
 */
@Slf4j
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {
    private static final String PAGE_INDEX = "role/index";
    private static final String PAGE_CREATE = "role/create";

    private static final String PAGE_EDIT = "role/edit";

    private static final String PAGE_ASSIGN_SHOW = "role/assignShow";

    private static final String PAGE_SUCCESS = "common/successPage";

    private static final String LIST_ACTION = "redirect:/role";

    @Reference
    private RoleService roleService;
    @Reference
    private PermissionService permissionService;

    @PreAuthorize("hasAuthority('role.show')")
    @RequestMapping
    public String findPage(@NonNull Model model, HttpServletRequest request) {
        Map<String, Object> filters = getFilters(request);
        PageInfo<Role> page = roleService.findPage(filters);
        model.addAttribute("page", page);
        model.addAttribute("filters", filters);
        return PAGE_INDEX;
    }


    /**
     * 跳转到新增页面
     *
     * @return
     */
    @PreAuthorize("hasAuthority('role.create')")
    @RequestMapping("/create")
    public String toCreate() {
        return PAGE_CREATE;
    }

    /**
     * 新增角色
     *
     * @param role
     * @return
     */
    @PreAuthorize("hasAuthority('role.create')")
    @RequestMapping("/save")
    public String saveRole(Role role) {
        Integer i = roleService.insert(role);
        return PAGE_SUCCESS;
    }

    /**
     * 根据id查找role
     *
     * @param model
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('role.edit')")
    @RequestMapping("/toEdit/{id}")
    public String toEdit(@NonNull Model model, @PathVariable("id") Long id) {
        log.debug("id = {}", id);
        //根据id获取role
        Role role = roleService.getById(id);
        model.addAttribute("role", role);
        return PAGE_EDIT;
    }
    @PreAuthorize("hasAuthority('role.edit')")
    @RequestMapping("/update")
    public String updateRole(Role role) {
        log.debug("role = {}", role);
        Integer i = roleService.update(role);
        return PAGE_SUCCESS;
    }
    @PreAuthorize("hasAuthority('role.delete')")
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        Integer i = roleService.delete(id);
        return LIST_ACTION;
    }

    @PreAuthorize("hasAuthority('role.assign')")
    @RequestMapping("/assignShow/{roleId}")
    public String assignPermissionShow(@PathVariable("roleId") Long roleId, Model model) {
        if (roleId == null) return null;
        List<Map<String, Object>> zNodes = permissionService.findPermissionByRoleId(roleId);
        model.addAttribute("zNodes", zNodes);
        model.addAttribute("roleId", roleId);
        return PAGE_ASSIGN_SHOW;
    }

    @PreAuthorize("hasAuthority('role.assign')")
    @RequestMapping("/assignPermission")
    public String assignPermission(@RequestParam("roleId") Long roleId,
                                   @RequestParam("permissionIds") Long[] permissionIds) {
        if (permissionIds == null) return null;

        Long[] noNullPermissionIds = Arrays.stream(permissionIds).filter(Objects::nonNull).toArray(Long[]::new);
        permissionService.assignPermissionsToRole(roleId, noNullPermissionIds);
        return PAGE_SUCCESS;
    }

//    @RequestMapping("/role/findRoles/{adminId}")
//    @ResponseBody
//    public Result findRolesByAdminId(@PathVariable("adminId") Long adminId) {
//        if (null == adminId) return Result.build(null, ResultCodeEnum.PARAM_ERROR);
//        List<Role> roleList = roleService.findRolesByAdminId(adminId);
//        return Result.ok(roleList);
//    }
}
